<template>
  <view class="exam-container">
    <!-- 加载状态 -->
    <view class="loading-overlay" v-if="loading">
      <view class="loading-spinner"></view>
      <text class="loading-text">题库加载中...</text>
    </view>
    
    <!-- 错误状态 -->
    <view class="error-overlay" v-else-if="error">
      <text class="error-icon">❌</text>
      <text class="error-text">{{ error }}</text>
      <text class="error-tip">即将返回上一页...</text>
    </view>
    
    <!-- 题目内容，仅在非加载状态且无错误时显示 -->
    <template v-else-if="questions && questions.length > 0">
      <!-- Background elements -->
      <view class="bg-gradient"></view>
      <view class="bg-pattern"></view>
      
      <!-- Floating decoration elements -->
      <view v-for="n in 5" :key="`dec-${n}`" class="floating-element" :style="{ 
        '--size': `${Math.random() * 6 + 3}rem`,
        '--x': `${Math.random() * 100}%`,
        '--y': `${Math.random() * 100}%`,
        '--duration': `${Math.random() * 20 + 20}s`,
        '--delay': `${Math.random() * 5}s`,
        '--opacity': `${Math.random() * 0.2 + 0.05}`
      }"></view>

      <!-- 顶部进度条 -->
      <view class="progress-wrapper">
        <view class="progress-info">
          <text class="progress-label">进度</text>
          <text class="progress-text">{{ currentIndex + 1 }}/{{ questions.length }}</text>
        </view>
        <view class="progress-bar">
          <view class="progress" :style="{ width: `${(currentIndex + 1) / questions.length * 100}%` }"></view>
        </view>
      </view>

      <!-- 滑动区域 -->
      <swiper 
        class="swiper-box" 
        :current="currentIndex"
        @change="handlePageChange"
        :duration="300"
      >
        <swiper-item v-for="(question, index) in questions" :key="question.id">
          <scroll-view class="question-scroll" scroll-y>
            <!-- 题目内容 -->
            <view class="question-card">
              <view class="question-header">
                <text class="question-number">第{{ index + 1 }}题</text>
                <view class="question-type">
                  <text class="type-text">{{ getQuestionTypeText(question.question_type) }}</text>
                </view>
              </view>
              
              <text class="question-content">{{ question.content }}</text>

              <!-- 题目图片 -->
              <view v-if="question.image_url" class="image-container">
                <image
                  :src="question.image_url"
                  mode="aspectFit"
                  class="question-image"
                  @tap="previewImage(question.image_url)"
                />
                <view class="image-overlay">
                  <view class="zoom-icon">
                    <text class="iconfont">&#xe6dd;</text>
                  </view>
                </view>
              </view>

              <!-- 选项列表 -->
              <view class="options-list">
                <view
                  v-for="(optionValue, optionKey) in question.options"
                  :key="optionKey"
                  class="option-item"
                  :class="{
                    'selected': userAnswers[index] === optionKey,
                    'correct': showAnswers[index] && question.answer === optionKey,
                    'wrong': showAnswers[index] && userAnswers[index] === optionKey 
                            && userAnswers[index] !== question.answer
                  }"
                  @tap="selectAnswer(index, optionKey)"
                >
                  <view class="option-label">{{ optionKey }}</view>
                  <text class="option-content">{{ optionValue }}</text>
                  <view class="check-indicator" v-if="userAnswers[index] === optionKey">
                    <text class="iconfont" v-if="showAnswers[index] && userAnswers[index] === question.answer">&#xe6da;</text>
                    <text class="iconfont" v-else-if="showAnswers[index] && userAnswers[index] !== question.answer">&#xe6db;</text>
                    <text class="iconfont" v-else>&#xe6dc;</text>
                  </view>
                </view>
              </view>

              <!-- 答案解析 -->
              <view v-if="showAnswers[index]" class="explanation">
                <view class="explanation-header">
                  <view class="correct-answer">
                    <text class="answer-label">正确答案：</text>
                    <text class="answer-value">{{ question.answer }}</text>
                  </view>
                  <view :class="['result-tag', userAnswers[index] === question.answer ? 'correct' : 'wrong']">
                    {{ userAnswers[index] === question.answer ? '回答正确' : '回答错误' }}
                  </view>
                </view>
                <view class="explanation-content">
                  <text class="explanation-title">答案解析：</text>
                  <text class="explanation-text">{{ question.explanation }}</text>
                </view>
              </view>
            </view>
          </scroll-view>
        </swiper-item>
      </swiper>

      <!-- 底部操作栏 -->
      <view class="bottom-bar">
        <button 
          class="nav-btn prev" 
          :disabled="currentIndex === 0"
          @tap="prevQuestion"
        >
          <text class="btn-text">上一题</text>
        </button>
        
        <button 
          class="submit-btn"
          v-if="!showAnswers[currentIndex]"
          @tap="submitAnswer"
        >
          <text class="btn-text">确定</text>
        </button>
        
        <button 
          class="nav-btn next" 
          :disabled="currentIndex === questions.length - 1"
          @tap="nextQuestion"
        >
          <text class="btn-text">下一题</text>
        </button>
      </view>
    </template>
  </view>
</template>

<script>
import { questionApi } from '@/services/api'

export default {
  data() {
    return {
      currentIndex: 0,
      questions: [],
      userAnswers: [],
      showAnswers: [],
      loading: true,
      examParams: null,
      startTime: null,
      error: null
    }
  },

  async onLoad() {
    try {
      // 显示加载提示
      uni.showLoading({
        title: '加载题目中...',
        mask: true
      });
      
      // 获取考试参数
      const examParams = uni.getStorageSync('examParams');
      if (!examParams) {
        throw new Error('考试参数不存在');
      }
      
      this.examParams = examParams;
      console.log('考试参数:', examParams);
      
      // 根据考试类型加载题目
      let response;
      try {
        if (examParams.examType === 'theory') {
          response = await questionApi.getExamQuestions(examParams.subject, examParams.vehicleType);
        } else if (examParams.examType === 'special') {
          response = await questionApi.getSpecialTraining(examParams.subject, examParams.vehicleType);
        } else if (examParams.examType === 'sequence') {
          response = await questionApi.getSequenceQuestions(examParams.subject);
        }
        
        console.log('API返回的原始数据:', response);
        
        // 检查response是否为有效数据
        if (!response) {
          throw new Error('未获取到题目数据');
        }
        
        // 确保response是数组
        const questionsArray = Array.isArray(response) ? response : (response.data || response.result || response.questions || []);
        
        if (!Array.isArray(questionsArray) || questionsArray.length === 0) {
          throw new Error('题目数据格式错误或为空');
        }
        
        // 数据预处理
        const questions = questionsArray.map((q, index) => {
          // 处理选项数据
          let options = {};
          if (Array.isArray(q.options)) {
            q.options.forEach((opt, idx) => {
              const key = String.fromCharCode(65 + idx); // A, B, C, D...
              options[key] = opt;
            });
          } else if (typeof q.options === 'object') {
            options = q.options;
          }
          
          // 确保每个题目都有必要的字段
          return {
            id: q.id || q._id || String(index + 1),
            content: q.content || q.question || q.title || '题目内容缺失',
            options: options,
            answer: q.answer || q.correct_answer || '',
            explanation: q.explanation || q.analysis || '暂无解析',
            question_type: q.question_type || q.type || 'single',
            image_url: q.image_url || q.imageUrl || q.img || ''
          };
        });
        
        console.log('处理后的第一道题目:', questions[0]);
        
        // 初始化考试数据
        this.questions = questions;
        this.userAnswers = new Array(questions.length).fill('');
        this.showAnswers = new Array(questions.length).fill(false);
        this.startTime = new Date();
        this.loading = false;
        this.error = null;
        
        // 存储考试信息
        uni.setStorageSync('examInfo', {
          subject: examParams.subject,
          vehicleType: examParams.vehicleType,
          examType: examParams.examType,
          startTime: this.startTime,
          questionCount: questions.length
        });
        
        console.log('题目加载完成，总数:', this.questions.length);
        
        // 使用nextTick确保DOM更新
        this.$nextTick(() => {
          this.$forceUpdate();
        });
        
      } catch (apiError) {
        console.error('API调用失败:', apiError);
        throw new Error('获取题目失败，请检查网络连接');
      }
      
    } catch (error) {
      console.error('加载题目失败:', error);
      this.error = error.message || '加载题目失败，请重试';
      this.loading = false;
      
      uni.showToast({
        title: this.error,
        icon: 'none',
        duration: 2000
      });
      
      // 返回上一页
      setTimeout(() => {
        uni.navigateBack();
      }, 2000);
      
    } finally {
      uni.hideLoading();
    }
  },

  methods: {
    getQuestionTypeText(type) {
      const typeMap = {
        'single': '单选题',
        'multiple': '多选题',
        'judge': '判断题'
      }
      return typeMap[type] || type;
    },

    handlePageChange(e) {
      this.currentIndex = e.detail.current;
    },

    selectAnswer(index, answer) {
      if (!this.showAnswers[index]) {
        this.$set(this.userAnswers, index, answer);
      }
    },

    async submitAnswer() {
      // 如果没有选择答案，提示用户
      if (!this.userAnswers[this.currentIndex]) {
        uni.showToast({
          title: '请选择答案',
          icon: 'none',
          duration: 2000
        });
        return;
      }

      // 标记当前题目已显示答案
      this.$set(this.showAnswers, this.currentIndex, true);
      
      // 获取当前题目和用户答案
      const question = this.questions[this.currentIndex];
      const userAnswer = this.userAnswers[this.currentIndex];
      const isCorrect = userAnswer === question.answer;
      
      // 保存答题记录
      try {
        await questionApi.saveRecord({
          questionId: question.id,
          userAnswer,
          isCorrect,
          subject: this.examParams.subject,
          vehicleType: this.examParams.vehicleType
        });
      } catch (error) {
        console.error('保存答题记录失败:', error);
        uni.showToast({
          title: '保存记录失败',
          icon: 'none',
          duration: 2000
        });
      }
      
      // 自动切换到下一题或显示结果
      if (this.currentIndex < this.questions.length - 1) {
        // 延迟切换到下一题，让用户有时间查看答案
        setTimeout(() => {
          this.nextQuestion();
        }, 2000);
      } else {
        // 如果是最后一题，显示结果
        setTimeout(() => {
          this.showResult();
        }, 2000);
      }
    },

    prevQuestion() {
      if (this.currentIndex > 0) {
        this.currentIndex--;
      }
    },

    nextQuestion() {
      if (this.currentIndex < this.questions.length - 1) {
        this.currentIndex++;
      } else {
        // 已经是最后一题，显示结果
        this.showResult();
      }
    },

    previewImage(url) {
      uni.previewImage({
        urls: [url]
      });
    },

    showResult() {
      // 检查是否所有题目都已回答
      const unansweredCount = this.userAnswers.filter(a => !a).length;
      
      if (unansweredCount > 0) {
        uni.showModal({
          title: '提示',
          content: `还有${unansweredCount}道题目未回答，确定要交卷吗？`,
          success: (res) => {
            if (res.confirm) {
              this.calculateResults();
            }
          }
        });
      } else {
        this.calculateResults();
      }
    },
    
    calculateResults() {
      // 计算正确题目数量
      const correctCount = this.userAnswers.filter((answer, index) => 
        answer === this.questions[index].answer
      ).length;
      
      const totalQuestions = this.questions.length;
      const answeredQuestions = this.userAnswers.filter(a => a).length;
      const wrongCount = answeredQuestions - correctCount;
      const accuracy = (correctCount / totalQuestions * 100).toFixed(1);
      
      // 计算用时
      const timeUsed = this.calculateTimeUsed();
      
      // 保存结果到本地存储，以便结果页面显示
      uni.setStorageSync('examResults', {
        totalQuestions,
        correctCount,
        wrongCount,
        accuracy,
        timeUsed
      });

      // 跳转到结果页面
      uni.redirectTo({
        url: `/pages/exam/result?correct=${correctCount}&total=${totalQuestions}&time=${timeUsed}`
      });
    },

    calculateTimeUsed() {
      if (!this.startTime) return '未计时';
      
      const endTime = new Date();
      const diffMs = endTime - this.startTime;
      
      // 转换为分钟和秒
      const minutes = Math.floor(diffMs / 60000);
      const seconds = Math.floor((diffMs % 60000) / 1000);
      
      return `${minutes}分${seconds}秒`;
    }
  }
}
</script>

<style lang="scss" scoped>
.exam-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  position: relative;
  overflow: hidden;
  background-color: #f9f9fd;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  
  // 加载状态
  .loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(255, 255, 255, 0.9);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    z-index: 9999;
    
    .loading-spinner {
      width: 80rpx;
      height: 80rpx;
      border: 6rpx solid #f3f3f3;
      border-top: 6rpx solid #3f6efa;
      border-radius: 50%;
      margin-bottom: 30rpx;
      animation: spin 1s linear infinite;
    }
    
    .loading-text {
      font-size: 30rpx;
      color: #333;
    }
    
    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }
  }
  
  // 错误状态
  .error-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(255, 255, 255, 0.9);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    z-index: 9999;
    
    .error-icon {
      font-size: 80px;
      color: #ff4650;
      margin-bottom: 20px;
    }
    
    .error-text {
      font-size: 30px;
      color: #333;
      margin-bottom: 20px;
    }
    
    .error-tip {
      font-size: 20px;
      color: #666;
    }
  }
  
  // Background elements
  .bg-gradient {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 45vh;
    background: linear-gradient(135deg, #3f6efa, #8c46e3);
    z-index: 0;
    transform: skewY(-5deg) translateY(-30%);
    border-bottom-left-radius: 30% 10%;
    border-bottom-right-radius: 30% 10%;
  }
  
  .bg-pattern {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image: url('data:image/svg+xml;utf8,<svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" fill="rgba(255,255,255,0.05)"/></svg>');
    background-size: 20px 20px;
    z-index: 0;
    opacity: 0.5;
  }
  
  // Floating decoration elements
  .floating-element {
    position: absolute;
    width: var(--size);
    height: var(--size);
    border-radius: 50%;
    background: linear-gradient(135deg, rgba(255,255,255,0.1), rgba(255,255,255,0.03));
    box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
    backdrop-filter: blur(5px);
    -webkit-backdrop-filter: blur(5px);
    border: 1px solid rgba(255, 255, 255, 0.05);
    top: var(--y);
    left: var(--x);
    z-index: 1;
    opacity: var(--opacity);
    animation: float var(--duration) infinite ease-in-out;
    animation-delay: var(--delay);
  }

  .progress-wrapper {
    padding: 20px 20px 10px;
    position: relative;
    z-index: 2;
    
    .progress-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;
      
      .progress-label {
        font-size: 14px;
        color: #666;
        font-weight: 500;
      }
      
      .progress-text {
        font-size: 14px;
        color: #333;
        font-weight: 600;
      }
    }
    
    .progress-bar {
      height: 6px;
      background-color: rgba(0, 0, 0, 0.05);
      border-radius: 3px;
      overflow: hidden;

      .progress {
        height: 100%;
        background: linear-gradient(90deg, #3f6efa, #8c46e3);
        transition: width 0.5s cubic-bezier(0.4, 0, 0.2, 1);
        border-radius: 3px;
      }
    }
  }

  .swiper-box {
    flex: 1;
    height: 0;
    position: relative;
    z-index: 5;
  }

  .question-scroll {
    height: 100%;
    padding: 5px 20px 20px;
  }

  .question-card {
    background-color: #fff;
    border-radius: 16px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 5px 20px rgba(0, 0, 0, 0.05);
    transform: translateY(0);
    transition: transform 0.3s ease;
    position: relative;
    z-index: 5;
    overflow: hidden;
    
    &:before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      height: 4px;
      background: linear-gradient(90deg, #3f6efa, #8c46e3);
      z-index: 1;
    }

    .question-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      .question-number {
        font-size: 18px;
        color: #333;
        font-weight: 600;
      }

      .question-type {
        background: rgba(63, 110, 250, 0.1);
        border-radius: 20px;
        padding: 4px 10px;
        
        .type-text {
          font-size: 13px;
          color: #3f6efa;
          font-weight: 500;
        }
      }
    }

    .question-content {
      font-size: 16px;
      color: #333;
      line-height: 1.6;
      margin-bottom: 20px;
      font-weight: 500;
    }
    
    .image-container {
      position: relative;
      width: 100%;
      margin-bottom: 20px;
      border-radius: 12px;
      overflow: hidden;
      box-shadow: 0 2px 15px rgba(0, 0, 0, 0.1);
      
      .question-image {
        width: 100%;
        height: 200px;
        display: block;
      }
      
      .image-overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.2);
        opacity: 0;
        transition: opacity 0.3s ease;
        display: flex;
        align-items: center;
        justify-content: center;
        
        .zoom-icon {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          background: rgba(255, 255, 255, 0.9);
          display: flex;
          align-items: center;
          justify-content: center;
          
          .iconfont {
            font-size: 20px;
            color: #333;
          }
        }
      }
      
      &:active .image-overlay {
        opacity: 1;
      }
    }

    .options-list {
      margin-bottom: 20px;
      
      .option-item {
        display: flex;
        align-items: center;
        padding: 15px;
        border: 1px solid #eee;
        border-radius: 12px;
        margin-bottom: 12px;
        transition: all 0.3s ease;
        position: relative;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.03);

        &:last-child {
          margin-bottom: 0;
        }

        &.selected {
          background-color: rgba(63, 110, 250, 0.05);
          border-color: #3f6efa;
        }

        &.correct {
          background-color: rgba(50, 180, 100, 0.05);
          border-color: #32b464;
        }

        &.wrong {
          background-color: rgba(255, 70, 80, 0.05);
          border-color: #ff4650;
        }

        .option-label {
          width: 30px;
          height: 30px;
          line-height: 30px;
          text-align: center;
          border-radius: 50%;
          margin-right: 12px;
          font-size: 14px;
          font-weight: 600;
          background-color: #f5f6fa;
          color: #666;
          transition: all 0.3s ease;
          flex-shrink: 0;
        }
        
        &.selected .option-label {
          background-color: #3f6efa;
          color: #fff;
        }
        
        &.correct .option-label {
          background-color: #32b464;
          color: #fff;
        }
        
        &.wrong .option-label {
          background-color: #ff4650;
          color: #fff;
        }

        .option-content {
          flex: 1;
          font-size: 15px;
          color: #333;
          line-height: 1.5;
        }
        
        .check-indicator {
          width: 24px;
          height: 24px;
          margin-left: 10px;
          flex-shrink: 0;
          display: flex;
          align-items: center;
          justify-content: center;
          
          .iconfont {
            font-size: 20px;
            
            &:first-child {
              color: #32b464;
            }
            
            &:nth-child(2) {
              color: #ff4650;
            }
            
            &:last-child {
              color: #3f6efa;
            }
          }
        }
      }
    }

    .explanation {
      background-color: #f9f9fd;
      border-radius: 12px;
      padding: 15px;
      animation: fadeIn 0.5s ease;

      .explanation-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;
        flex-wrap: wrap;

        .correct-answer {
          font-size: 15px;
          display: flex;
          align-items: center;
          
          .answer-label {
            color: #666;
            margin-right: 5px;
          }
          
          .answer-value {
            color: #333;
            font-weight: 600;
          }
        }

        .result-tag {
          font-size: 13px;
          padding: 4px 10px;
          border-radius: 20px;
          font-weight: 500;

          &.correct {
            color: #32b464;
            background-color: rgba(50, 180, 100, 0.1);
          }

          &.wrong {
            color: #ff4650;
            background-color: rgba(255, 70, 80, 0.1);
          }
        }
      }

      .explanation-content {
        .explanation-title {
          font-size: 14px;
          color: #666;
          margin-bottom: 8px;
          display: block;
        }

        .explanation-text {
          font-size: 14px;
          color: #333;
          line-height: 1.6;
        }
      }
    }
  }

  .bottom-bar {
    padding: 15px 20px calc(15px + env(safe-area-inset-bottom));
    background-color: #fff;
    box-shadow: 0 -5px 20px rgba(0, 0, 0, 0.05);
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: relative;
    z-index: 10;

    .nav-btn {
      min-width: 100px;
      height: 44px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 22px;
      font-size: 14px;
      background-color: #f5f6fa;
      color: #333;
      transition: all 0.3s ease;
      border: none;
      
      .btn-text {
        margin: 0 5px;
      }

      &:disabled {
        opacity: 0.5;
      }
      
      &:active {
        transform: scale(0.97);
      }
    }

    .submit-btn {
      flex: 1;
      height: 44px;
      border-radius: 22px;
      font-size: 15px;
      background: linear-gradient(90deg, #3f6efa, #8c46e3);
      color: #fff;
      border: none;
      margin: 0 10px;
      font-weight: 500;
      transition: all 0.3s ease;
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0 4px 10px rgba(63, 110, 250, 0.3);
      
      &:active {
        transform: scale(0.97);
        box-shadow: 0 2px 5px rgba(63, 110, 250, 0.3);
      }
    }
  }
}

// Animations
@keyframes float {
  0%, 100% {
    transform: translate(0, 0) rotate(0deg);
  }
  25% {
    transform: translate(10px, 10px) rotate(5deg);
  }
  50% {
    transform: translate(0, 20px) rotate(0deg);
  }
  75% {
    transform: translate(-10px, 10px) rotate(-5deg);
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style> 